package com.bootdo.common.utils;

import com.bootdo.common.wxpay.MD5Util;

import java.util.*;

public class PayCheckSginUtils {
    /**
     * 验证微信回调的签名  防止别人恶意篡改
     * @param inmap
     * @param apiKey
     * @return
     */
    public synchronized static boolean checkWxSgin(Map inmap, String apiKey){
        SortedMap<String, String> map = mapChange(inmap);
        StringBuffer sb = new StringBuffer();
        Set es = map.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if (!"sign".equals(k) && null != v && !"".equals(v) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + apiKey);
        /** 验证的签名 */
        String sign = MD5Util.MD5Encode(sb.toString(), "utf-8").toUpperCase();

        /** 微信端返回的合法签名 */
        String validSign = ((String) map.get("sign")).toUpperCase();
        //System.err.println("===================>回调参数组装"+sb.toString());
        System.err.println("===================>回调参数签名"+validSign);
        System.err.println("===================>自己计算签名"+sign);
        return validSign.equals(sign);
    }


    /**
     * 旧map转新map
     * @param map
     * @return
     */
    private  static  SortedMap mapChange(Map map){
        SortedMap m = new TreeMap();

        Set<String> set = map.keySet();
        if(null != set){
            for(String k1 : set){
                m.put(k1.replace("xml.", ""), map.get(k1));
            }
        }
        if(m.containsKey("root.name")){
            m.remove("root.name");
        }
        return m ;
    }



    /**
     * 支付宝回调签名验证
     * @param req
     * @param resp
     * @param alipayKey
     * @return
     * @throws AlipayApiException
     *//*
	public static synchronized boolean checkAliSgin(HttpServletRequest req,HttpServletResponse resp,String alipayPublicKey) throws AlipayApiException{
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = req.getParameterMap();
		System.err.println("mapSize="+requestParams.size());
		Iterator iter = requestParams.keySet().iterator();
		while(iter.hasNext()){
			 String name = (String) iter.next();
		     String[] values = (String[]) requestParams.get(name);
		     String valueStr = "";
		     for (int i = 0; i < values.length; i++) {
		         valueStr = (i == values.length - 1) ? valueStr + values[i]
		                     : valueStr + values[i] + ",";
		     }
		     //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
		     System.err.println("k="+name+"v="+valueStr);
		     params.put(name, valueStr);
		}
		System.err.println("支付宝回调111==》"+params.get("sign"));
		boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayPublicKey, "utf-8", "RSA2");
		return signVerified;
	}*/



}
